package com.lqd.mall.sso.service.impl;

import com.lqd.mall.basis.constant.Constants;
import com.lqd.mall.basis.constant.SecurityConstants;
import com.lqd.mall.basis.exception.ExceptionCast;
import com.lqd.mall.basis.response.Result;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.sso.vo.LoginVo;
import com.lqd.mall.interaction.system.vo.LoginUserVo;
import com.lqd.mall.redis.utils.RedisUtils;
import com.lqd.mall.security.utils.SecurityUtils;
import com.lqd.mall.sso.manager.factory.AsyncFactory;
import com.lqd.mall.sso.service.ISysLoginService;
import com.lqd.mall.system.service.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 零起点
 * @create 2022-02-13 9:38
 */
@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public LoginUserVo login(LoginVo loginVo) {
        if (loginVo == null) {
            ExceptionCast.cast("登录信息不能为空");
        }
        String captcha = redisUtils.get(Constants.CAPTCHA_CODE_KEY + loginVo.getUuid());
        redisUtils.delete(Constants.CAPTCHA_CODE_KEY + loginVo.getUuid());
        if (StringUtils.isEmpty(captcha)) {
            AsyncFactory.recordLogininfor(loginVo.getUsername(), Constants.LOGIN_FAIL,
                    "登录失败");
            ExceptionCast.cast("登录失败");
        }

        if (!captcha.equals(loginVo.getCode())) {
            AsyncFactory.recordLogininfor(loginVo.getUsername(), Constants.LOGIN_FAIL,
                    "验证吗错误");
            ExceptionCast.cast("验证吗错误");
        }


        Result<LoginUserVo> info = remoteUserService.getUserInfo(loginVo.getUsername(), SecurityConstants.INNER);
        if (!info.isSuccess()) {
            AsyncFactory.recordLogininfor(loginVo.getUsername(), Constants.LOGIN_FAIL,
                    "账号不存在");
            ExceptionCast.cast("账号不存在");
        }

        if (!SecurityUtils.matchesPassword(loginVo.getPassword(),info.getData().getSysUser().getPassword() )) {

            AsyncFactory.recordLogininfor(loginVo.getUsername(), Constants.LOGIN_FAIL,
                    "账号或密码错误");
            ExceptionCast.cast("账号或密码错误");
        }
        AsyncFactory.recordLogininfor(loginVo.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
        return info.getData();
    }

    @Override
    public void logout(String name) {
        AsyncFactory.recordLogininfor(name, Constants.LOGOUT, "退出登录成功");
    }
}
